<?php
// $_SERVER['SERVER_NAME'];
// $_SERVER['REQUEST_URI'];

/* TODO
 * Query string validation
 * for security.
 * REFERER CHECK
 */

function get_json($array) {
	$output = "[";
	$length = sizeof($array);
	$i = 0;
	foreach ($array as $row) {
		$output .= "{";
		foreach ($row as $key => $val) {
			$output .= '"' . $key . '"' . ':' .
			'"' . $val . '"';
		}
		$output .= "}";
		if (++$i < $length)
			$output .= ",";
	}
	$output .= "]";
	return $output;
}

$qry = $_GET['q'];
if ( str_replace(" ", "", $qry) == "" ) {
  print "[]";
  return;
}

$qry = str_replace(" ", "%", $qry);

$conn = mysql_connect('localhost', 'diycity', 'diycitykr');

if (!$conn)
  {
    die('Connect Error (' . mysql_error() . ') ');
  }
mysql_select_db("diycity",$conn);

$query = "SELECT address_string FROM address_suggest_sigugun" . 
  " WHERE address_string LIKE \"%" . $qry . "%\" LIMIT 10";

$result = mysql_query($query);
if (!$result)
  {
    echo mysql_error();
  }

$output = array();

while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
  {
    $output[] = $row;
  }

print get_json($output);

?>
